package com.qianbao.controller.v1.sms;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.qianbao.components.excepion.ExceptionEnum;
import com.qianbao.components.svresut.Result;
import com.qianbao.components.svversion.ApiVersion;
import com.qianbao.components.uuid.SVUuidTool;
import com.qianbao.domain.sms.SVSmsEntity;
import com.qianbao.domain.sms.SVVerfiySmsCodeEntity;
import com.qianbao.service.sms.SVSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@ApiVersion(1)
@RequestMapping("/sms/{version}/")
public class SmsController {


    @Autowired
    private SVSmsService service;


    /**
     * 发送验证码方法
     * @param requestEntity
     * @return
     */
    @RequestMapping("/send-sms")
    @ResponseBody
    public Result sendSms(@Valid SVSmsEntity requestEntity){

        String sendCode = createRandomVcode();

        requestEntity.setId(SVUuidTool.getNumberUUID());
        requestEntity.setSign("小牛");
        requestEntity.setCreate_time(this.getNowDate());
        requestEntity.setUpdate_time(this.getNowDate());
        requestEntity.setTemplate_code("SMS_168820267-股市书籍");
        requestEntity.setParams(sendCode);



        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","LTAIEVSclvB8Hnl0",
                "cIFOEtXwBWksyd1FHsEzvd9ZxPQftZ");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", requestEntity.getPhone());
        request.putQueryParameter("SignName", "万鼎");
        request.putQueryParameter("TemplateCode", "SMS_168820267");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+sendCode+"\"}");


        try {
            client.getCommonResponse(request);

            // 保存验证码到数据库
            service.saveSms(requestEntity);

            return Result.success(
                    ExceptionEnum.Sms_Send_Success.getCode(),
                    ExceptionEnum.Sms_Send_Success.getMessage(),
                    Collections.emptyMap());
        } catch (ServerException e) {
            e.printStackTrace();
            return Result.fail(ExceptionEnum.Sms_Send_fail.getCode(),
                    ExceptionEnum.Sms_Send_fail.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            return Result.fail(ExceptionEnum.Sms_Send_fail.getCode(),
                    ExceptionEnum.Sms_Send_fail.getMessage());
        }

    }


    /**
     * 验证 验证码接口
     * @param entity 验证码实体类
     * @return
     */
    @ResponseBody
    @RequestMapping("/verify-sms-code")
    public Result verifiySmsCode(@Valid SVVerfiySmsCodeEntity entity){

        String code = service.findCodeByPhone(entity.getPhone());

        Result result;

        if (code.equals(entity.getCode())){

            HashMap<String,String> data = new HashMap<>();
            data.put("success","1");

           result = Result.success(ExceptionEnum.Sms_verify_Success.getCode(),ExceptionEnum.Sms_verify_Success.getMessage(),data);
        }else {
            result = Result.fail(ExceptionEnum.Sms_verify_Fail.getCode(),ExceptionEnum.Sms_verify_Fail.getMessage());
        }

        return result;
    }







    /*随机产生6位数字验证码*/
    private String createRandomVcode(){
        String vcode = "" ;
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            int index = random.nextInt(10);
            vcode = vcode + index;
        }
        return vcode;
    }



    /*获取当前的时间*/
    private Date getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(0);
        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }










}
